<template>
  <div id="orderPayment">
    <!-- <top-bar :title="title" :showBack="false">
            <md-icon class="back_btn" name="snyc_nav_fh" @click="cannelOrderBtn" slot="left"></md-icon>
    </top-bar>-->
    <div class="orderPaymentwapper">
      <div class="orderPayment_box">
        <div class="order_list">
          <p class="surplus_time">剩余支付时间</p>
          <p class="surplus_time_number">
            <span>{{minutes_one}}</span>
            <span>{{minutes_two}}</span>
            <b>:</b>
            <span>{{seconds_one}}</span>
            <span>{{seconds_two}}</span>
          </p>
          <p class="actual_pay">
            ¥
            <span>{{getBalanceInfoData?getBalanceInfoData.payAmt:""}}</span>
          </p>
          <p class="order_pay" v-show="IscouponAmt">原价￥{{getOrderInfoData?getOrderInfoData.order_amt:''}}</p>
          <p class="coupon_change">
            <span v-show="IscouponAmt">
              优惠券已抵扣
              <b>{{getBalanceInfoData?getBalanceInfoData.couponAmt:""}}元</b>
            </span>
            <span @click="getchargesDetails">
              查看费用明细
              <img src="@/assets/imgs/arrow_right.png" />
            </span>
          </p>
          <p class="detail_hx"></p>
          <p class="detail-head">
            <md-icon name="snkc_xcqx_time" slot="left" class="snkc_xcqx_time"></md-icon>
            <b>{{getStartTime}}-{{getEndTime}}</b>
            <span
              v-if="(getOrderInfoData?getOrderInfoData.order_type:'') == '拼车'"
            >{{getOrderInfoData?getOrderInfoData.order_num:''}}人{{getOrderInfoData?getOrderInfoData.order_type:''}}</span>
            <span v-if="(getOrderInfoData?getOrderInfoData.order_type:'') == '包车'">{{getOrderInfoData?getOrderInfoData.car_type:''}}</span>
            <span v-show="speedstatus">走高速</span>
          </p>
          <ul class="detail_list">
            <li>
              <md-icon name="shangchedian" slot="left" class="shangchedian"></md-icon>
              <span>{{getstartRoute}} . {{getorigin}}</span>
            </li>
            <li>
              <md-icon name="xiachedian" slot="left" class="shangchedian"></md-icon>
              <span>{{getendRoute}} . {{getdestination}}</span>
            </li>
            <li v-show="Isremarks">
              <md-icon name="dt_bz" slot="left" class="snkc_xcqx_time"></md-icon>
              <span>{{getOrderInfoData?getOrderInfoData.remarks:''}}</span>
            </li>
            <li v-show="Isorder_type">
              <md-icon name="snkc_xcqx_dj" slot="left" class="snkc_xcqx_time"></md-icon>
              <span>{{getOrderInfoData?getOrderInfoData.passenger_name:''}} {{userPhone}}</span>
            </li>
          </ul>
        </div>
        <div class="pay_bottom_btn">
          <p class="orderPayBtn" @click="orderPay">立即支付</p>
          <p class="cannelOrderPayBtn" @click="cannelOrderBtn">取消订单</p>
        </div>
        <md-popup v-model="payBox" position="bottom">
          <md-popup-title-bar title="支付车费" cancel-text="取消" @cancel="cancelPayBox"></md-popup-title-bar>
          <div class="pay_box_ct">
            <p class="pay_box_amt_hd">
              合计支付
              <span>{{getBalanceInfoData?getBalanceInfoData.payAmt:""}}元</span>
            </p>
            <p class="pay_box_com">
              优惠券
              <span @click="choiceCoupon">
                {{couponTitle}}
                <img src="@/assets/imgs/arrow_right.png" />
              </span>
            </p>
            <p class="pay_box_text">实际支付金额</p>
            <p class="pay_box_amt">
              ¥
              <span>{{getBalanceInfoData?getBalanceInfoData.payAmt:""}}</span>
            </p>
            <div class="payType">
              <ul class="choice-payment-method">
                <li @click="balanceMethod">
                  <img src="@/assets/imgs/snyc_zf_yezf.png" />
                  <span>余额支付</span>
                  <b>
                    <em>余额&nbsp;{{BalancePayAmt}}</em>
                    <i class="choice-payment-right" :class="{active:paymentMethod == 'balance'}"></i>
                  </b>
                </li>
                <li @click="wechatMethod">
                  <img src="@/assets/imgs/cz_wx_icon@2x.png" />
                  <span>微信支付</span>
                  <b>
                    <i class="choice-payment-right" :class="{active:paymentMethod == 'wechat'||paymentMethod == 'miniprogram'||paymentMethod=='h5wx'}"></i>
                  </b>
                </li>
                <li @click="alipayMethod" v-if="hasAlipay">
                  <img src="@/assets/imgs/cz_zfb_icon@2x.png" />
                  <span>支付宝支付</span>
                  <b>
                    <i class="choice-payment-right" :class="{active:paymentMethod == 'alipay'}"></i>
                  </b>
                </li>
              </ul>
            </div>
            <p class="orderPayBtns" @click="paySubmit">确认支付</p>
          </div>
        </md-popup>
        <md-popup v-model="cannelOrderBox" position="bottom">
          <md-popup-title-bar title="取消订单" cancel-text="取消" @cancel="cancelBox"></md-popup-title-bar>
          <div class="pay_box_ct">
            <div :class="{pay_box_cancel: IsPayBoxCancel}">
              <p class="pay_box_cancel_hd">请选择取消订单的原因(必选)：</p>
              <md-radio
                class="tripcancel_radio_btn"
                ref="radio"
                :options="cancelData"
                :default-index="0"
                icon="circle-right"
                icon-inverse="circle"
                icon-position="right"
                @change="onRadioChange"
              ></md-radio>
            </div>
            <p class="orderPayBtns" @click="onBackButton">提交</p>
          </div>
        </md-popup>
        <md-popup v-model="isKeyBoardShow" position="bottom">
          <md-popup-title-bar title="请输入支付密码" cancel-text="取消" @cancel="hidePopUp"></md-popup-title-bar>
          <div class="keyBoardShow">
            <p class="paymoney">¥{{getBalanceInfoData?getBalanceInfoData.payAmt:""}}</p>
            <ul class="paypwd_box">
              <li>
                <span v-show="payPwd.length >= 1"></span>
              </li>
              <li>
                <span v-show="payPwd.length >= 2"></span>
              </li>
              <li>
                <span v-show="payPwd.length >= 3"></span>
              </li>
              <li>
                <span v-show="payPwd.length >= 4"></span>
              </li>
              <li>
                <span v-show="payPwd.length >= 5"></span>
              </li>
              <li>
                <span v-show="payPwd.length >= 6"></span>
              </li>
            </ul>
            <md-number-keyboard v-model="isKeyBoardShow" type="simple" @enter="onNumberEnter" @delete="onNumberDelete"></md-number-keyboard>
          </div>
        </md-popup>
      </div>
    </div>
    <md-dialog title="确认" :closable="false" v-model="actDialog.open" :btns="actDialog.btns">请确认支付是否已经完成</md-dialog>
  </div>
</template>

<script>
import '@/assets/svgs/snyc_nav_fh.svg';
import '@/assets/svgs/shangchedian.svg';
import '@/assets/svgs/xiachedian.svg';
import '@/assets/svgs/snkc_xcqx_time.svg';
import '@/assets/svgs/dt_bz.svg';
import '@/assets/svgs/snkc_xcqx_dj.svg';
import '@/assets/svgs/xc_question.svg';
import '@/assets/svgs/Fill.svg';
import '@/assets/svgs/tishi.svg';
import { Icon, Field, FieldItem, Toast, Radio, Popup, PopupTitleBar, NumberKeyboard, Dialog } from 'mand-mobile';
import TopBar from '@/components/TopBar';
import Loading from '@/components/loading';
import { decryptByDESModeEBC, encryptByDESModeEBC } from '@/common/encrypt';
import { Base64 } from 'js-base64';
import http from '@/common/http';
import { mapGetters, mapActions, mapMutations } from 'vuex';
import Utils from '@/common/pakjUtils';
import { loadavg } from 'os';
var CryptoJS = require('crypto-js');
var moment = require('moment');
moment.locale('zh-cn');
const STORAGE_CALLED_PAY = 'CALLED_PAY';
const STORAGE_ORDER_NO = 'ORDER_NO';
export default {
  components: {
    [Icon.name]: Icon,
    [TopBar.name]: TopBar,
    [Field.name]: Field,
    [Toast.name]: Toast,
    [Radio.name]: Radio,
    [Popup.name]: Popup,
    [Dialog.name]: Dialog,
    [PopupTitleBar.name]: PopupTitleBar,
    [NumberKeyboard.name]: NumberKeyboard,
    [FieldItem.name]: FieldItem
  },
  data() {
    return {
      title: '订单支付',
      couponTitle: '',
      couponId: '',
      payType: '', // 支付方式
      BalancePayAmt: '',
      paymentMethod: '',
      isKeyBoardShow: false,
      payPwd: '',
      minutes_one: '',
      minutes_two: '',
      seconds_one: '',
      seconds_two: '',
      orderTimer: '',
      PaymentStatusTimer: '',
      orderNo: undefined,
      Isorder_type: true, // 是否显示乘车人
      Isremarks: true, // 是否显示大件行李
      speedstatus: true,
      IscouponAmt: true, // 是否显示优惠券金额
      payBox: false,
      cannelOrderBox: false,
      IsPayBoxCancel: false,
      cancelText: '行程有变',
      cancelData: [
        {
          text: '行程有变'
        }
      ],
      actDialog: {
        open: false,
        btns: [
          {
            text: '重新支付',
            handler: this.onActCancel
          },
          {
            text: '已完成支付',
            handler: this.onActConfirm
          }
        ]
      }
    };
  },
  created() {
    let orderno = this.$route.query.orderno;
    if (orderno) {
      this.orderNo = orderno;
    } else {
      let orderno = localStorage.getItem(STORAGE_ORDER_NO);
      if (orderno) {
        this.orderNo = orderno;
      } else {
        Dialog.alert({
          title: '错误',
          content: '找不到订单号',
          confirmText: '确定',
          onConfirm: () => {
            this.$router.push({
              name: 'Home'
            });
          }
        });
        return;
      }
    }
    this.getOrderInfo(this.orderNo).then(() => {
      let payCountTime = parseInt(this.getOrderInfoData.payCountTime);
      this.orderTimer = setInterval(() => {
        // let time = (parseInt(this.getOrderInfoData.deadline) - new Date().getTime()) / 1000;
        let time = payCountTime--;
        if (time > 0) {
          // let minutes = Math.floor(time / 60) > 9 ? Math.floor(time / 60) : '0' + Math.floor(time / 60);
          // let seconds = Math.floor(time % 60) > 9 ? Math.floor(time % 60) : '0' + Math.floor(time % 60);
          // this.expiredTime = minutes + ':' + seconds;
          this.minutes_one = Math.floor(Math.floor(time / 60) / 10);
          this.minutes_two = Math.floor(Math.floor(time / 60) % 10);
          if (this.minutes_one < 1) {
            this.minutes_one = '0';
          }
          this.seconds_one = Math.floor(Math.floor(time % 60) / 10);
          if (this.seconds_one < 1) {
            this.seconds_one = '0';
          }
          this.seconds_two = Math.floor(Math.floor(time % 60) % 10);
        } else {
          clearInterval(this.orderTimer);
          this.minutes_one = '0';
          this.minutes_two = '0';
          this.seconds_one = '0';
          this.seconds_two = '0';
          Dialog.alert({
            icon: 'tishi',
            content: '订单支付已超时，请重新下单',
            confirmText: '确认',
            onConfirm: () => {
              let params = {
                order_no: this.orderNo,
                order_status: '3',
                reason: '超时未支付，系统自动取消'
              };
              this.$store
                .dispatch('updateOrderInfo', params)
                .then(() => {
                  this.resetOrder();
                  clearInterval(this.orderTimer);
                  this.$router.replace({
                    name: 'Home'
                  });
                })
                .catch(() => {});
            }
          });
        }
      }, 1000);
      // 是否显示乘车人
      if (this.getOrderInfoData.is_self === '0') {
        this.Isorder_type = false;
      }
      // 是否显示大件行李
      if (this.getOrderInfoData.remarks === '无') {
        this.Isremarks = false;
      }
      // 是否显示走高速
      if (this.getOrderInfoData.speed_status === '0') {
        this.speedstatus = false;
      }
      // 订单是否支付
      if (this.getOrderInfoData.pay_status !== '待支付') {
        this.$router.push({
          name: 'MyAllot'
        });
      }
      // 订单是否取消
      // if (this.getOrderInfoData.order_status_id === '3') {
      //     this.$router.push({
      //         name: 'Home'
      //     });
      // }
    });
    // 初始化页面是否有优惠券
    let couponId = this.$route.query.coupon_id;
    let couponTitle = this.$route.query.coupon_title;
    if (couponId && couponTitle) {
      this.couponTitle = couponTitle;
      this.couponId = couponId;
      let params = {
        order_no: this.orderNo,
        user_coupon_id: this.couponId
      };
      // 每次确定完优惠券后调用支付金额接口
      this.getBalancePayAmt(params).then(() => {
        this.BalancePayAmt = this.getBalanceInfoData.accountBalance;
        if (this.getBalanceInfoData.couponAmt === '0.00') {
          this.IscouponAmt = false;
        }
        this.detectDefaultPaymentMethod();
      });
    } else {
      // 获取优惠券
      this.getDefaultCoupon(this.orderNo).then(() => {
        let params = {
          order_no: this.orderNo
        };
        if (sessionStorage['iscoupon'] === '2') {
          // 有优惠券不使用
          this.couponTitle = '有可用优惠券';
        } else {
          if (this.getcouponInfoData.user_coupon_id) {
            this.couponTitle = this.getcouponInfoData.coupon_title;
            params.user_coupon_id = this.getcouponInfoData.user_coupon_id;
            this.couponId = this.getcouponInfoData.user_coupon_id;
          } else {
            this.couponTitle = this.getcouponInfoData;
          }
        }
        // 每次确定完优惠券后调用支付金额接口
        this.getBalancePayAmt(params).then(() => {
          this.BalancePayAmt = this.getBalanceInfoData.accountBalance;
          if (this.getBalanceInfoData.couponAmt === '0.00') {
            this.IscouponAmt = false;
          }
          this.detectDefaultPaymentMethod();
        });
      });
    }
    let calledPay = localStorage.getItem(STORAGE_CALLED_PAY);
    if (calledPay === '1') {
      this.actDialog.open = true;
    }
    let param = {
      order_no: this.$route.query.orderno
    };
    Loading.show();
    http.post('pakj/order/getCOrderLText', param).then(res => {
      Loading.hide();
      console.log(res.data);
      if (res.data.code === '000000') {
        if (res.data.data.reason_label) {
          var textArry = res.data.data.reason_label.split(',');
          if (textArry.length > 7) {
            this.IsPayBoxCancel = true;
          }
          this.cancelData = [];
          for (var i in textArry) {
            var textObj = {
              text: textArry[i],
              value: (parseInt(i) + 1).toString()
            };
            this.cancelData.push(textObj);
          }
          // this.cancelData.push({
          //     text: '其它',
          //     value: ''
          // });
        }
      } else {
        Dialog.alert({
          title: '提示',
          content: res.data.msg,
          confirmText: '确定'
        });
      }
    });
    // 检测是否拉起支付窗口
    if (this.$route.name === 'OrderPaymentPay') {
      this.payBox = true;
    } else {
      this.payBox = false;
    }
  },
  beforeDestroy() {
    clearInterval(this.orderTimer);
  },
  methods: {
    ...mapActions([
      'WXsubmitPayment',
      'getOrderInfo',
      'getDefaultCoupon',
      'getBalancePayAmt',
      'createBalancePay',
      'getbalancePayOrder',
      'miniprogramPayment',
      'h5WxPayment'
    ]),
    ...mapMutations(['resetOrder']),
    onBackButton() {
      Dialog.confirm({
        title: '取消行程',
        content: '您是否要取消当前订单',
        confirmText: '确认取消',
        onConfirm: () => {
          let params = {
            order_no: this.orderNo,
            order_status: '3',
            reason: this.cancelText
          };
          this.$store
            .dispatch('updateOrderInfo', params)
            .then(() => {
              this.resetOrder();
              clearInterval(this.orderTimer);
              this.$router.replace({
                name: 'Home',
                query: {}
              });
            })
            .catch(() => {});
        }
      });
    },
    // 未支付取消订单
    cannelOrderBtn() {
      this.cannelOrderBox = true;
    },
    onRadioChange(obj) {
      this.cancelText = obj.text;
    },
    goback() {
      return new Promise(resolve => {
        Dialog.confirm({
          title: '取消行程',
          content: '您是否要取消当前订单',
          confirmText: '确认取消',
          onConfirm: () => {
            let params = {
              order_no: this.orderNo,
              order_status: '3'
            };
            this.$store
              .dispatch('updateOrderInfo', params)
              .then(() => {
                this.resetOrder();
                this.$router.replace({
                  name: 'Home'
                });
                clearInterval(this.orderTimer);
                resolve();
              })
              .catch(() => {
                resolve();
              });
          }
        });
      });
    },
    getSelected() {
      console.log(this.$refs['radio'].getSelectedValue().value);
    },
    detectDefaultPaymentMethod() {
      if (parseInt(this.BalancePayAmt) > 0) {
        this.paymentMethod = 'balance';
      } else {
        this.wechatMethod();
      }
    },
    // 拉起支付
    orderPay() {
      this.payBox = true;
      this.$router.push({
        name: 'OrderPaymentPay',
        query: {
          orderno: this.orderNo
        }
      });
    },
    // 费用明细
    getchargesDetails() {
      this.$router.push({
        name: 'ChargesDetails',
        query: {
          orderno: this.orderNo,
          couponid: this.couponId
        }
      });
    },
    onNumberEnter(val) {
      if (this.payPwd.length < 6) {
        this.payPwd += val;
      }
      if (this.payPwd.length === 6) {
        // 余额支付
        let param = {
          payPwd: CryptoJS.MD5(this.payPwd).toString()
        };
        this.createBalancePay(param)
          .then(() => {
            let params = {
              order_no: this.orderNo
            };
            if (this.couponId) {
              this.couponTitle = this.getcouponInfoData.coupon_title;
              params.user_coupon_id = this.couponId;
            } else {
              if (sessionStorage['iscoupon'] === '2') {
                this.couponTitle = '有可用优惠券';
              } else {
                this.couponTitle = this.getcouponInfoData;
              }
            }
            this.getbalancePayOrder(params)
              .then(() => {
                Dialog.alert({
                  title: '提示',
                  content: '支付成功',
                  confirmText: '确定',
                  onConfirm: () => {
                    sessionStorage['iscoupon'] = '1';
                    window.location.href = '/orderdetail?orderno=' + this.orderNo;
                    // if (Utils.isMiniProgram()) {
                    //     window.location.href = "#/orderdetail?orderno=" + this.orderNo;
                    // } else {
                    //     window.location.href = "/orderdetail?orderno=" + this.orderNo;
                    // }
                    // this.$router.push({
                    //     name: "OrderDetail",
                    //     query: {
                    //         orderno: this.orderNo
                    //     }
                    // })
                  }
                });
              })
              .catch(error => {
                let str = error.toString().split(':');
                let code = str[1].trim();
                let msgText = str[2];
                if (code === '200008') {
                  Dialog.alert({
                    title: '提示',
                    content: msgText,
                    confirmText: '确定',
                    onConfirm: () => {
                      this.$router.push({
                        name: 'MyAllot'
                      });
                    }
                  });
                } else if (code === '200006') {
                  Dialog.alert({
                    title: '提示',
                    content: msgText,
                    confirmText: '确定',
                    onConfirm: () => {
                      this.isKeyBoardShow = false;
                    }
                  });
                }
              });
          })
          .catch(error => {
            let str = error.toString().split(':');
            let code = str[1].trim();
            let msgText = str[2];
            console.log(code);
            if (code === '200028') {
              Dialog.confirm({
                title: '提示',
                content: '您未设置支付密码，请去设置支付密码',
                confirmText: '确定',
                onConfirm: () => {
                  this.$router.push({
                    name: 'ChangePayPasswordPhone'
                  });
                }
              });
            } else if (code === '200029') {
              Dialog.alert({
                title: '提示',
                content: msgText,
                confirmText: '确定',
                onConfirm: () => {
                  this.payPwd = '';
                }
              });
            } else {
              Dialog.alert({
                title: '提示',
                content: msgText,
                confirmText: '确定',
                onConfirm: () => {
                  this.payPwd = '';
                }
              });
            }
          });
      }
    },
    onNumberDelete() {
      if (this.payPwd === '') {
        return false;
      }
      this.payPwd = this.payPwd.substr(0, this.payPwd.length - 1);
    },
    hidePopUp() {
      this.isKeyBoardShow = false;
      this.payPwd = '';
    },
    cancelPayBox() {
      this.payBox = false;
      this.$router.push({
        name: 'OrderPayment',
        query: {
          orderno: this.orderNo
        }
      });
    },
    cancelBox() {
      this.cannelOrderBox = false;
    },
    // 余额支付
    balanceMethod() {
      if (parseFloat(this.getBalanceInfoData.accountBalance) >= parseFloat(this.getBalanceInfoData.payAmt)) {
        this.paymentMethod = 'balance';
      } else {
        Dialog.alert({
          title: '提示',
          content: '余额不足，请使用其他支付方式',
          confirmText: '确定'
        });
      }
    },
    // 微信支付
    wechatMethod() {
      switch (Utils.getCurrentEnv()) {
        case 'mini':
          this.paymentMethod = 'miniprogram';
          break;
        case 'wx':
          this.paymentMethod = 'wechat';
          break;
        case 'h5':
          this.paymentMethod = 'h5wx';
          break;
      }
    },
    // 支付宝支付
    alipayMethod() {
      this.paymentMethod = 'alipay';
    },
    // 选择优惠券
    choiceCoupon() {
      if (this.couponId && this.couponTitle) {
        let query = {
          order_no: this.orderNo,
          coupon_id: this.couponId
        };
        this.$router.push({
          name: 'MyUseCoupon',
          query: query
        });
      } else {
        if (this.getcouponInfoData === '暂无可用优惠券') {
          Dialog.alert({
            title: '提示',
            content: '暂无可用优惠券',
            confirmText: '确定'
          });
          return false;
        }
        let query = {
          order_no: this.orderNo
        };
        if (this.getcouponInfoData.user_coupon_id) {
          query.coupon_id = this.getcouponInfoData.user_coupon_id;
        }
        this.$router.push({
          name: 'MyUseCoupon',
          query: query
        });
      }
    },
    paySubmit() {
      if (this.paymentMethod === 'balance') {
        console.info('使用余额支付');
        // 选择余额支付
        this.isKeyBoardShow = true;
      } else if (this.paymentMethod === 'wechat') {
        console.info('使用微信公众号支付');
        // 选择微信支付
        let p = {
          order_no: this.orderNo,
          pay_type: '1001'
        };
        if (this.couponId) {
          p.user_coupon_id = this.couponId;
        }
        this.WXsubmitPayment(p)
          .then(() => {
            let params = this.getWXPaymentInfoData.JSPParam;
            wx.config({
              debug: false,
              appId: params['appId'],
              timestamp: params['timestamp'],
              nonceStr: params['noncestr'],
              signature: params['signature'],
              jsApiList: ['chooseWXPay']
            });
            wx.ready(() => {
              wx.chooseWXPay({
                timestamp: params['timestamp'],
                nonceStr: params['noncestr'],
                package: 'prepay_id=' + params['package'], // TODO May need remove 'prepay\_id='
                signType: 'MD5', // TODO If this didn't work . Use 'SHA1'.
                paySign: params['paySign'],
                success: res => {
                  if (res.errMsg === 'chooseWXPay:ok') {
                    this.queryPaymentStatus();
                  }
                },
                fail: res => {
                  this.$store
                    .dispatch('checkPaymentStatus', this.orderNo)
                    .then(() => {
                      this.$router.push({
                        name: 'OrderDetail',
                        query: {
                          orderno: this.orderNo
                        }
                      });
                    })
                    .catch(reason => {
                      Dialog.alert({
                        title: '错误',
                        content: '支付失败',
                        confirmText: '确定'
                      });
                    });
                }
              });
            });
          })
          .catch(reason => {
            if (reason.message === '200008') {
              this.$router.push({
                name: 'OrderDetail',
                query: {
                  orderno: this.orderNo
                }
              });
            } else {
              Dialog.alert({
                title: '错误',
                content: '支付失败',
                confirmText: '确定'
              });
            }
          });
      } else if (this.paymentMethod === 'miniprogram') {
        console.info('使用小程序支付');
        Loading.show();
        let params = {
          order_no: this.orderNo,
          pay_type: '1001'
        };
        if (this.couponId) {
          params.user_coupon_id = this.couponId;
        }
        this.miniprogramPayment(params)
          .then(res => {
            res.orderNo = this.orderNo;
            let jsonStr = JSON.stringify(res);
            let base64str = Base64.encode(jsonStr);
            wx.miniProgram.redirectTo({
              url: '/pages/payment/payment?info=' + base64str
            });
          })
          .catch(reason => {
            if (reason.message === '200008') {
              this.$router.push({
                name: 'OrderDetail',
                query: {
                  orderno: this.orderNo
                }
              });
            } else {
              Dialog.alert({
                title: '错误',
                content: '支付失败',
                confirmText: '确定'
              });
            }
          });
      } else if (this.paymentMethod === 'alipay') {
        console.log('使用支付宝支付');
        let parameters = {
          order_no: this.orderNo,
          pay_type: '1002'
        };
        if (this.couponId) {
          parameters.user_coupon_id = this.couponId;
        }
        this.h5WxPayment(parameters)
          .then(() => {
            localStorage.setItem(STORAGE_ORDER_NO, this.orderNo);
            localStorage.setItem(STORAGE_CALLED_PAY, '1');
            let htmlStr = this.getH5wxPaymentInfo.AlipayBody;
            const div = document.createElement('div'); // 创建div
            div.innerHTML = htmlStr; // 将返回的form 放入div
            document.body.appendChild(div);
            document.forms[0].submit();
            this.actDialog.open = true;
          })
          .catch(reason => {
            if (reason.message === '200008') {
              this.$router.push({
                name: 'OrderDetail',
                query: {
                  orderno: this.orderNo
                }
              });
            } else {
              Dialog.alert({
                title: '错误',
                content: '支付失败',
                confirmText: '确定'
              });
            }
          });
      } else if (this.paymentMethod === 'h5wx') {
        console.info('使用H5微信支付');
        let p = {
          order_no: this.orderNo,
          pay_type: '1001'
        };
        if (this.couponId) {
          p.user_coupon_id = this.couponId;
        }
        this.h5WxPayment(p)
          .then(() => {
            localStorage.setItem(STORAGE_ORDER_NO, this.orderNo);
            localStorage.setItem(STORAGE_CALLED_PAY, '1');
            window.location.href = this.getH5wxPaymentInfo.JSPParam.mweb_url;
            this.actDialog.open = true;
          })
          .catch(reason => {
            if (reason.message === '200008') {
              this.$router.push({
                name: 'OrderDetail',
                query: {
                  orderno: this.orderNo
                }
              });
            } else {
              Dialog.alert({
                title: '错误',
                content: '支付失败',
                confirmText: '确定'
              });
            }
          });
      }
    },
    onActConfirm() {
      localStorage.removeItem(STORAGE_CALLED_PAY);
      localStorage.removeItem(STORAGE_ORDER_NO);
      this.actDialog.open = false;
      Loading.show();
      this.queryPaymentStatus(); // 查询支付状态
      // setTimeout(() => {
      //     Loading.hide();
      //     this.$store
      //         .dispatch('checkPaymentStatus', this.orderNo)
      //         .then(() => {
      //             this.$router.push({
      //                 name: 'OrderDetail',
      //                 query: {
      //                     orderno: this.orderNo
      //                 }
      //             });
      //         })
      //         .catch(reason => {
      //             Dialog.alert({
      //                 title: '错误',
      //                 content: '支付失败',
      //                 confirmText: '确定'
      //             });
      //         });
      // }, 1000);
    },
    onActCancel() {
      localStorage.removeItem(STORAGE_CALLED_PAY);
      localStorage.removeItem(STORAGE_ORDER_NO);
      this.actDialog.open = false;
    },
    // 查询支付状态
    queryPaymentStatus() {
      let params = {
        type: '1',
        orderNo: this.orderNo
      };
      this.$store
        .dispatch('paymentStatus', params)
        .then(() => {
          Toast({
            content: '支付成功',
            duration: 2000,
            hasMask: true
          });
          Loading.hide();
          clearInterval(this.PaymentStatusTimer);
          setTimeout(() => {
            this.$router.push({
              name: 'OrderDetail',
              query: {
                orderno: this.orderNo
              }
            });
          }, 2000);
        })
        .catch(error => {
          let str = error.toString().split(':');
          let code = str[1].trim();
          let msgText = str[2];
          if (code === '5') {
            // 正在查询支付结果
            Loading.show('正在查询支付结果');
            // this.$router.push({
            //     name: 'OrderPayment',
            //     query: {
            //         orderno: this.orderNo
            //     }
            // });
            this.PaymentStatusTimer = setInterval(() => {
              this.queryPaymentStatus();
            }, 5000);
          } else if (code === '2') {
            // 订单未支付
            Toast({
              content: '订单未支付',
              duration: 2000,
              hasMask: true
            });
            Loading.hide();
            clearInterval(this.PaymentStatusTimer);
          } else if (code === '4') {
            // 支付失败
            Toast({
              content: '支付失败',
              duration: 2000,
              hasMask: true
            });
            Loading.hide();
            clearInterval(this.PaymentStatusTimer);
          }
        });
    }
  },
  computed: {
    ...mapGetters([
      'getOrderInfoData',
      'getOrderId',
      'getWXPaymentInfoData',
      'getcouponInfoData',
      'getBalanceInfoData',
      'getbalancePayOrderData',
      'getH5wxPaymentInfo'
    ]),
    userPhone() {
      var str = this.getOrderInfoData;
      if (!str) {
        return '';
      }
      return decryptByDESModeEBC(str.passenger_phone);
    },
    getStartTime() {
      var str = this.getOrderInfoData;
      if (!str) {
        return '';
      }
      let startMoment = moment(str.travel_time, 'x').format('MMMDo HH:mm');
      return startMoment;
    },
    getEndTime() {
      var str = this.getOrderInfoData;
      if (!str) {
        return '';
      }
      let endMoment = moment(str.travel_end_time, 'x').format('HH:mm');
      return endMoment;
    },
    hasAlipay() {
      if (Utils.getCurrentEnv() === 'h5') {
        return true;
      } else {
        return false;
      }
    },
    getstartRoute() {
      var str = this.getOrderInfoData;
      if (!str) {
        return '';
      }
      if (str.start_route.length > 3) {
        return str.start_route.substring(0, 3) + '...';
      } else {
        return str.start_route;
      }
    },
    getendRoute() {
      var str = this.getOrderInfoData;
      if (!str) {
        return '';
      }
      if (str.end_route.length > 3) {
        return str.end_route.substring(0, 3) + '...';
      } else {
        return str.end_route;
      }
    },
    getorigin() {
      var str = this.getOrderInfoData;
      if (!str) {
        return '';
      }
      if (str.origin.length > 22) {
        return str.origin.substring(0, 22) + '...';
      } else {
        return str.origin;
      }
    },
    getdestination() {
      var str = this.getOrderInfoData;
      if (!str) {
        return '';
      }
      if (str.destination.length > 22) {
        return str.destination.substring(0, 22) + '...';
      } else {
        return str.destination;
      }
    }
  }
};
</script>

<style lang="stylus">
#orderPayment {
  height: 100vh;
  background-color: color-primary-background;

  p {
    display: block;
    margin-block-start: 0px;
    margin-block-end: 0px;
    margin-inline-start: 0px;
    margin-inline-end: 0px;
  }

  .md-radio .md-field .md-field-item.md-radio-item .md-field-item-inner {
    padding: 15px;
  }

  .paypwd_box {
    height: 110px;
    border-radius: 10px;
    border: 1px solid #979797;
    margin: 0px 30px;
    margin-top: 50px;
  }

  .paypwd_box li {
    float: left;
    border-right: solid 1px #979797;
    width: 112px;
    height: 110px;
  }

  .paypwd_box li:nth-of-type(6) {
    border-right: none;
  }

  .paypwd_box li span {
    height: 28px;
    width: 28px;
    background-color: #333;
    border-radius: 50%;
    display: inline-block;
    position: relative;
    top: 40px;
    left: 40px;
  }

  .paymoney {
    font-size: 40px;
    color: #333;
    text-align: center;
    padding-top: 84px;
  }

  .keyBoardShow {
    height: 800px;
    background-color: #fff;
  }

  .orderPaymentwapper {
  }

  .orderPayment_box {
  }

  .order_list {
    background-color: #fff;
  }

  .detail-head {
    font-size: 28px;
    color: #333;
    padding: 30px 30px 10px 35px;
  }

  .detail-head b {
    font-weight: 400;
    margin-left: 10px;
  }

  .detail-head em {
    margin: 0px 5px;
  }

  .detail-head span {
    font-size: 20px;
    color: #FF6917;
    border: solid 1px #FF6917;
    padding: 4px 10px;
    margin-left: 20px;
    position: relative;
    bottom: 4px;
    border-radius: 7px;
  }

  .detail_list {
    margin: 0px 30px;
    padding-bottom: 25px;
  }

  .detail_list li {
    font-size: 24px;
    color: #666;
    padding: 10px 0px;
  }

  .detail_list li span {
    margin-left: 12px;
  }

  .detail_hx {
    height: 1px;
    background-color: #E0E0E0;
  }

  .detail_moeny {
    margin: 0px 30px;
    font-size: 24px;
    color: #666;
    height: 80px;
    line-height: 80px;
  }

  .detail_moeny span {
    float: right;
    color: #FF6917;
  }

  .couponhd {
    height: 80px;
    margin: 0px 30px;
    line-height: 80px;
    font-size: 26px;
    color: #666;
  }

  .orderTime {
    text-align: center;
    margin-top: 10px;
    font-size: 26px;
    color: #666;
  }

  .orderTime span {
    color: #FF6917;
  }

  .pay_bottom_btn {
    position: absolute;
    bottom: 20px;
    width: 100%;
  }

  .orderPayBtn {
    width: 94%;
    height: 98px;
    line-height: 98px;
    font-size: 36px;
    text-align: center;
    background-color: #FF6917;
    color: #fff;
    margin: 0px 3% 0px 3%;
    border-radius: 10px;
  }

  .cannelOrderPayBtn {
    width: 94%;
    height: 98px;
    line-height: 98px;
    font-size: 36px;
    text-align: center;
    border: 1px solid rgba(224, 224, 224, 1);
    color: #666;
    margin: 20px 3% 0px 3%;
    border-radius: 10px;
  }

  .orderPayBtns {
    width: 94%;
    height: 98px;
    line-height: 98px;
    font-size: 36px;
    text-align: center;
    background-color: #FF6917;
    color: #fff;
    margin: 40px 3% 0px 3%;
    border-radius: 10px;
  }

  .md-field-item-title {
    font-size: 26px;
  }

  .md-field-item-content {
    font-size: 26px;
  }

  .shangchedian {
    position: relative;
    width: 16px;
    height: 16px;
  }

  .snkc_xcqx_time {
    position: relative;
    width: 16px;
    height: 16px;
  }

  .xc_question {
    position: relative;
    width: 24px;
    height: 24px;
    left: 10px;
    top: 4px;
  }

  .md-radio-content {
    font-size: 26px;
    color: #666;
  }

  .md-radio-content img {
    width: 44px;
    height: 44px;
    margin-right: 15px;
    position: relative;
    top: 15px;
  }

  .choice-payment-method {
    background-color: #fff;
  }

  .choice-payment-method li {
    padding: 0px 30px;
    font-size: 26px;
    color: #666;
    line-height: 88px;
    height: 88px;
    border-bottom: #e0e0e0 solid 1px;
  }

  .choice-payment-method li img {
    width: 44px;
    height: 44px;
    position: relative;
    top: 12px;
  }

  .choice-payment-method li span {
    margin-left: 20px;
  }

  .choice-payment-method li b {
    float: right;
    color: #999999;
    font-weight: 400;
  }

  .choice-payment-method li b em {
    margin-right: 10px;
    font-style: normal;
  }

  .choice-payment-right {
    display: inline-block;
    background-color: #fff;
    width: 36px;
    height: 36px;
    border: 1px solid #e3e3e3;
    border-radius: 50%;
    position: relative;
    top: 12px;
  }

  .choice-payment-method li b .active {
    background: url('../../assets/imgs/ddzf_icon_pre@2x.png') no-repeat center center;
    background-size: contain;
    border-color: #fff;
    width: 36px;
    height: 36px;
  }

  .surplus_time {
    text-align: center;
    font-size: 28px;
    color: #333;
    padding-top: 40px;
  }

  .surplus_time_number {
    text-align: center;
    font-size: 28px;
    color: #333;
    padding-top: 10px;
  }

  .surplus_time_number span {
    padding: 5px 10px;
    background-color: #D8D8D8;
    margin-left: 10px;
    color: #666;
  }

  .surplus_time_number b {
    margin-left: 10px;
    font-weight: 400;
  }

  .actual_pay {
    text-align: center;
    font-size: 28px;
    color: #FF6917;
    padding-top: 10px;
  }

  .actual_pay span {
    font-size: 40px;
  }

  .order_pay {
    text-align: center;
    font-size: 24px;
    color: #999;
  }

  .coupon_change {
    text-align: center;
    font-size: 24px;
    color: #999;
    padding-top: 10px;
    padding-bottom: 32px;
  }

  .coupon_change b {
    font-weight: 400;
    color: #FF6917;
  }

  .coupon_change span {
    margin-left: 10px;
  }

  .coupon_change span img {
    width: 12px;
    height: 20px;
  }

  .pay_box_ct {
    background-color: #fff;
    padding-bottom: 20px;
  }

  .pay_box_amt_hd {
    font-size: 26px;
    color: #666;
    height: 68px;
    line-height: 68px;
    margin: 0px 30px;
  }

  .pay_box_amt_hd span {
    float: right;
  }

  .pay_box_com {
    font-size: 26px;
    color: #666;
    height: 68px;
    line-height: 68px;
    margin: 0px 30px;
  }

  .pay_box_com span {
    float: right;
    color: #FF6917;
  }

  .pay_box_com span img {
    width: 12px;
    height: 20px;
    margin-left: 5px;
  }

  .pay_box_text {
    font-size: 26px;
    color: #666;
    text-align: center;
  }

  .pay_box_amt {
    font-size: 26px;
    color: #333;
    text-align: center;
    margin-top: 10px;
  }

  .pay_box_amt span {
    font-size: 40px;
    margin-top: 10px;
  }

  .pay_box_cancel {
    height: 48vh;
    overflow-y: auto;
  }

  .pay_box_cancel_hd {
    padding: 10px 30px;
    font-size: 30px;
    color: #333;
  }

  .md-radio-item {
    margin-bottom: 10px;
  }

  .md-icon-circle-right {
    width: 36px;
    height: 36px;
  }

  .md-icon-circle {
    width: 36px;
    height: 36px;
  }
}
</style>
